package com.shuo.controller;

import com.shuo.model.User;
import com.shuo.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Random;

/**
 * 测试结论: @Transaction只对1个方法生效,即被注解的方法; eg: A,B,C都有事务注解, C调用AB则此时AB自身的事务失效
 */
@ResponseBody
@Controller
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    private Random random = new Random();

    @RequestMapping("add")
    public Object add(String name) {
        User user = new User(name, random.nextInt(4));
        userService.add(user);
        return user;
    }

    @RequestMapping("update")
    public Object update(int id, String name) {
        User user = new User(name, random.nextInt(4));
        user.setId(id);
        userService.update(user);
        return user;
    }

    @RequestMapping("delete")
    public Object delete(int id) {
        userService.delete(id);
        return id;
    }

    /**
     * 添加成功
     *
     * @return
     */
    @RequestMapping("testA")
    public String testA() {
        userService.testA();
        return "ok";
    }

    /**
     * 添加失败, 回滚
     *
     * @return
     */
    @RequestMapping("testB")
    public String testB() {
        userService.testB();
        return "ok";
    }

    /**
     * A,B均添加成功! 都无回滚
     *
     * @return
     */
    @RequestMapping("testC")
    public String testC() {
        userService.testC();
        return "ok";
    }

    /**
     * A,B均添加成功! 都无回滚
     *
     * @return
     */
    @RequestMapping("testD")
    public String testD() {
        userService.testD();
        return "ok";
    }

    /**
     * A,B均添加失败! 都回滚
     *
     * @return
     */
    @RequestMapping("testE")
    public String testE() {
        userService.testE();
        return "ok";
    }

}
